import React, {
    Component
} from 'react';
import GridTable from '../../components/display/gridTable';
import ScModal from '../../components/feedback/scModal';
import {
    Button,
    Input,
    Spin,
    Row,
    Col,
    Divider,
    Tooltip,
    Modal,
    Radio,
    message
} from 'antd';
import {
    findStubList,
    getStubGroupDetail,
    updateStubStatus,
    stubRemoteUpdate
} from '../../fetch/fetchApi';
import PropsType from "prop-types";
import RemoteUpgrade from '../operation/stubQuery/remoteUpgrade';
import {
    UpdateStatus,
    StubStatus
} from '../operation/stubQuery/updateStatus';
import UpgradeSuccessModal from '../operation/stubQuery/upgradeSuccessModal';
import moment from 'moment';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

class Epile extends Component {
    constructor(props) {
        super(props);
        this.props = props;
        this.state = {
            gridData: null,
            loadingmes: '查询',
            loading: !1,
            btnloading: !1,
            spinLoading: !1,
            esData: null,
            pagination: {
                total: 0
            }
        };
        this.init();
        window.LayoutTab.tabParam && setTimeout(() => {
            this.queryChargeInfo();
        });
    }

    init() {
        this.query = {
            page: '1',
            pagecount: '10'
        };
        this.stubGroupType = {
            '0': '公共',
            '1': '个人',
            '2': '专用开放',
            '3': '专用内部'
        };
        this.params = {};
        window.LayoutTab && window.LayoutTab.tabParam && (this.query['stubGroupId'] = window.LayoutTab.tabParam.stubGroupId);
        // 设置表头
        this.tableColumns = [{
            title: '电桩编号',
            dataIndex: 'key',
            key: 'key',
        }, {
            title: '桩群名称',
            dataIndex: 'stubGroupName',
            key: 'stubGroupName',
        }, {
            title: '设备类型',
            dataIndex: 'type',
            key: 'type',
            render: (text, record) => (<div>{text === 0 ? '交流' : '直流'}</div>)
        }, {
            title: '当前状态',
            dataIndex: 'status',
            key: 'status',
            className: 'column-nowrap',
            render: (text, record) => (<div>{StubStatus[text.substr(0, 2)]||"未知("+text+")"}</div>)
        }, {
            title: '最大功率',
            dataIndex: 'kw',
            key: 'kw',
        }, {
            title: '托管到期',
            dataIndex: 'downtime',
            key: 'downtime',
            render: (text, record) => (<div>
                    {text?(moment(text)>=moment(Date.now())?
                        <div style={{'color':'green'}}>{moment(text).format("YYYY-MM-DD")}</div>:
                        <div style={{'color':'red'}}>{moment(text).format("YYYY-MM-DD")}</div>)
                        :'--'}
                </div>)
        }, {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <div className="action-wrap">
            {record.stubGroupId !== '2' && record.stubGroupId !== 'beta' && <a href="javascript:void(0);" onClick={() => this.showEsDetail(record.stubGroupId, '电站详情')}>电站详情</a>}
            {record.stubGroupId !== '2' && record.stubGroupId !== 'beta' && <Divider type="vertical" />}
            <a href="javascript:void(0);" onClick={() => this.openTab({
                        'keyId': record.key,
                        'stubId': record.key
                    }, {
                        'key': 'orderlist',
                        titleText: '订单列表'
                    })}>订单列表</a>
            <br/>
            <a href="javascript:void(0);" onClick={() => this.showUpdateStatusModal(record.status,record.key)}>修改状态</a>
            <Divider type="vertical" />
            <a href="javascript:void(0);" onClick={(e) => this.showRemoteUpgradeModal({
                        stubIds: record.key,
                        modelNos: record.modelNo
                    })}>固件升级</a>
            </div>
            )
        }];
    }

    // 显示电站详情
    showEsDetail(id, title) {
        this.setState({
            width: 800,
            modalVisible: !0,
            modalTitle: title
        });
        this.setState({
            spinLoading: !0
        });
        this.getEsDetail(id).then((data) => {
            this.setState({
                esData: data,
                spinLoading: !1
            });
        });
    }

    // 获取电站详情
    async getEsDetail(id) {
        try {
            const resData = await getStubGroupDetail({
                stubGroupId: id
            });
            if (resData.data.code === '200') {
                const result = resData.data.data;
                return result;
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 固件升级
    showRemoteUpgradeModal = (params = {}) => {
        if (!params.stubIds || !params.modelNos) {
            message.error("桩编号或型号为空！");
            return;
        }
        this.setState({
            remoteUpgradeVisible: true,
            remoteUpgradeParams: {
                stubIds: params.stubIds,
                modelNos: params.modelNos
            }
        })
    }

    // 取消弹窗
    cancel() {
        this.setState({
            modalVisible: !1,
            confirmLoading: !1
        });
    }

    // 打开tab
    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    // fetch DataSource
    async findStubList() {
        this.setState({
            loading: !0,
            btnloading: !0
        });
        try {
            const resData = await findStubList(this.query);
            if (resData.data.code === '200') {
                const pagination = {
                    total: resData.data.pageLimit.totalCount,
                    onShowSizeChange: (current) => {
                        this.turnPage(current)
                    },
                    onChange: (current) => {
                        this.turnPage(current)
                    }
                }
                this.setState({
                    pagination
                });
                return resData.data.data;
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 跳转页码
    turnPage(current) {
        this.query['page'] = current.toString();
        this.queryChargeInfo();
    }

    // 提交查询
    queryChargeInfo() {
        this.findStubList().then((data) => {
            this.setState({
                loading: !1,
                btnloading: !1,
                gridData: data
            });
        });
    }

    searchChargeInfo() {
        this.query.page = '1';
        this.state.pagination.current = 1;
        this.setState({
            pagination: this.state.pagination
        });
        this.queryChargeInfo();
    }

    // 注入电桩编号参数
    pileInputHandler(e) {
        this.query['stubId'] = e.target.value.toString();
    }

    showUpdateStatusModal = (status, stubId) => {
        this.currentStubId = stubId;
        this.currentStatus = status;
        this.setState({
            updateStatusVisible: true,
            currentStatus: status
        })
    }

    handleUpdateStatusCancel = (e) => {
        this.setState({
            updateStatusVisible: false
        })
    }

    handleUpdateStatus = (e) => {
        this.currentStatus = e;
    }

    handleStatusChange = (e) => {
        this.currentStatus = e.target.value;
    }

    handleUpdateStatusOk = (e) => {
        this.setState({
            updateStatusConfirmLoading: true,
            currentStatus: this.currentStatus
        })
        const res = updateStubStatus({
            stubId: this.currentStubId,
            status: this.currentStatus
        })
        res.then((data) => {
            if (data.data.code === "200") {
                this.handleUpdateStatusCancel();
                this.queryChargeInfo();
            }
            this.setState({
                updateStatusConfirmLoading: false
            })
        }).catch((ex) => {
            console.log(ex);
            this.setState({
                updateStatusConfirmLoading: false
            })
        })
    }

    handleRemoteUpgradeOk = (e) => {
        if (JSON.stringify(this.upgradeParams) === "{}") {
            message.error("参数缺失");
            return;
        }
        this.setState({
            remoteUpgradeConfirmLoading: true
        });
        stubRemoteUpdate(this.upgradeParams).then((data) => {
            if (data.data.code === '200') {
                message.success("升级成功");
                this.setState({
                    upgradeSuccessModalVisible: true
                })
            } else {
                console.log(data);
            }
            this.setState({
                remoteUpgradeConfirmLoading: false,
                remoteUpgradeVisible: false
            });
        }).catch((ex) => {
            console.log(ex);
            message.error("接口异常！");
            this.setState({
                remoteUpgradeConfirmLoading: false
            });
        })
    }

    handleRemoteUpgradeCancel = (e) => {
        this.setState({
            remoteUpgradeVisible: false
        })
    }

    handleRemoteUpgrade = (e) => {
        this.upgradeParams = e;
    }

    handleUpSuccessModalCancel = () => {
        this.setState({
            upgradeSuccessModalVisible: false
        })
    }

    render() {
        const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col lg={8} xl={4}>
            <Input placeholder="电桩编号精确查询" onChange={this.pileInputHandler.bind(this)}/>
          </Col>
          <div  className="button-inlineBlock">
            <Button type="primary" onClick={this.searchChargeInfo.bind(this)}>{this.state.loadingmes}</Button>
          </div>
        </Row>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
        <ScModal
        width={this.state.width}
        modalVisible={this.state.modalVisible}
        modalTitle={this.state.modalTitle}
        modalContent={<div className="sc-modal-scroll">
            {this.state.spinLoading && <Spin className={'loadingMiddle'}/>}
            {this.state.esData && <div className="modal-list"><div className={"modal-flex"}>
            <div className={"modal-flex-1"}>
              <ul>
                <li>
                  <strong>电站名称:</strong>
                  <span>{this.state.esData.name}</span>
                </li>
                <li>
                  <strong>所在城市</strong>
                  <span>{this.state.esData.cityStr}</span>
                </li>
                <li>
                  <strong>电站地址</strong>
                  <Tooltip placement="topLeft" title={this.state.esData.address}>
                    <span>{this.state.esData.address}</span>
                  </Tooltip>
                </li>
                <li>
                  <strong>运营类型</strong>
                  <span>{this.state.esData.type === 1 ? '自营' : '非自营'}</span>
                </li>
                <li>
                  <strong>电站类型</strong>
                  <span>{this.stubGroupType[this.state.esData.stubGroupType]}</span>
                </li>
                <li>
                  <strong>服务时间</strong>
                  <span>{this.state.esData.serviceTime}</span>
                </li>
                <li>
                  <strong>是否带枪</strong>
                  <span>{this.state.esData.hasGun === 1 ? '是' : '否'}</span>
                </li>
                <li>
                    <strong>车位引导</strong>
                    <Tooltip placement="topLeft" title={this.state.esData.stubGroupInfo}>
                    <span>{this.state.esData.stubGroupInfo}</span>
                    </Tooltip>
                </li>
                <li>
                  <strong>车位描述</strong>
                  <Tooltip placement="topLeft" title={this.state.esData.parkingInfo}>
                  <span>{this.state.esData.parkingInfo}</span>
                  </Tooltip>
                </li>
                <li>
                  <strong>停车费</strong>
                  <Tooltip placement="topLeft" title={this.state.esData.parkingFeeInfo}>
                  <span>{this.state.esData.parkingFeeInfo}</span>
                  </Tooltip>
                </li>
                <li>
                  <strong>电站公告</strong>
                  <span>{this.state.esData.noticInfo}</span>
                </li>
                <li>
                  <strong>漫游状态</strong>
                  <span>{this.state.esData.enableRoaming === 1 ? '漫游' : '非漫游'}</span>
                </li>
                <li>
                  <strong>电站状态</strong>
                  <span>{this.state.esData.isBuilded === 1 ? '上线' : '下线'}</span>
                </li>
                <li>
                  <strong>所属商户</strong>
                  <span>{this.state.esData.equipmentOwnerName}</span>
                </li>
                <li>
                  <strong>上线时间</strong>
                  <span>{this.state.esData.startTime}</span>
                </li>
              </ul>
            </div>
            <div className={"modal-flex-1"}>
              <ul>
                <li>
                  <strong>充电价格</strong>
                  <Tooltip placement="topLeft" title={this.state.esData.totalFeeInfo.replace('#', '\n')}>
                    <span>{this.state.esData.totalFeeInfo.replace('#', '\n')}</span>
                  </Tooltip>
                </li>
              </ul>
            </div>
          </div></div>}
            </div>}
        footer={null}
        cancel={this.cancel.bind(this)}
        />
      </div> <
            Modal title = "修改状态"
        visible = {
            this.state.updateStatusVisible
        }
        confirmLoading = {
            this.state.updateStatusConfirmLoading
        }
        onOk = {
            this.handleUpdateStatusOk
        }
        onCancel = {
                this.handleUpdateStatusCancel
            } >
            <UpdateStatus currentStatus={this.state.currentStatus} handle={this.handleUpdateStatus}/>
        </Modal> <Modal title = "远程升级"
        visible = {
            this.state.remoteUpgradeVisible
        }
        confirmLoading = {
            this.state.remoteUpgradeConfirmLoading
        }
        onOk = {
            this.handleRemoteUpgradeOk
        }
        onCancel = {
                this.handleRemoteUpgradeCancel
            } >
            <RemoteUpgrade params={this.state.remoteUpgradeParams} handle={this.handleRemoteUpgrade}/> </Modal> <UpgradeSuccessModal onAdd = {
            this.props.onAdd
        }
        handleCancel = {
            this.handleUpSuccessModalCancel
        }
        visible = {
            this.state.upgradeSuccessModalVisible
        }/> </div > ;

        return Content;
    }
}

export default Epile;

Epile.propTypes = {
    onAdd: PropsType.func
}